﻿using System;


    public  class Capture_Window_Pic
    {
        [System.Runtime.InteropServices.DllImport("user32.dll")]
        public static extern IntPtr GetForegroundWindow();

        [System.Runtime.InteropServices.DllImport("user32.dll")]
        public static extern bool PrintWindow(IntPtr hwnd, IntPtr hdcBlt, uint nFlags);

        [System.Runtime.InteropServices.DllImport("user32.dll")]
        public static extern IntPtr GetWindowRect(IntPtr hwnd, out RECT lpRect);

        [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
        public struct RECT
        {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;
        }

        public static void  caputure_pic(string filename)
        {
            IntPtr hwnd = Capture_Window_Pic.GetForegroundWindow(); // 获取当前活动窗口的句柄

            Capture_Window_Pic.RECT windowRect;
            Capture_Window_Pic.GetWindowRect(hwnd, out windowRect); // 获取窗口的位置和大小

            int width = windowRect.Right - windowRect.Left;
            int height = windowRect.Bottom - windowRect.Top;

            System.Drawing.Bitmap screenshot = new System.Drawing.Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(screenshot))
            {
                IntPtr hdc = graphics.GetHdc();
                Capture_Window_Pic.PrintWindow(hwnd, hdc, 0); // 将窗口内容绘制到图形上下文
                graphics.ReleaseHdc(hdc);
            }

            screenshot.Save(filename, System.Drawing.Imaging.ImageFormat.Png); // 保存截图
        }
    }
